const department = require("../model/departmentModel");

/**
 * 获取学院总数
 * @returns Promise
 */
exports.departmentCount = async () => {
  return await department.count();
};

/**
 * 获取学院列表
 * @returns Promise
 */
exports.getDepartments = async (
  searchContent,
  pageIndex = 1,
  pageSize = 12
) => {
    const match = searchContent ? {
        $match: {
            isDelete: 0,
            $or: [{ departmentName: { $regex: new RegExp(searchContent) } }],
          },
        }
        : 
        {
          $match: {
            isDelete: 0,
          }
      };
        
    return await department.aggregate([
      match,
      {
        $lookup: {
          from: "deans",
          localField: "departmentLeader",
          foreignField: "deanNo",
          as: "dean",
        },
      },
      {
        $skip: (pageIndex - 1) * pageSize,
      },
      {
        $limit: pageSize,
      },
      {
        $sort: {
          studentInSchoolDate: -1,
        },
      },
    ]);
}

/**
 * 根据ID删除一个学院
 * @param {String} _id
 * @returns
 */
exports.deleteDepartmentById = async (_id) => {
  return await department.updateOne({ _id }, { isDelete: 1 });
};

/**
 * 增加一个学院
 * @param {Department} department
 * @returns
 */
exports.addDepartment = async (depart) => {
  return new department({
    ...depart,
  }).save();
};

/**
 * 修改学院信息
 * @param {Department} depart
 * @returns
 */
exports.updateDepartment = async (depart) => {
  return await department.updateOne({ _id: depart._id }, { ...depart });
};


exports.findDepartmentById = async (id) => {
  return await department.findOne({_id:id,isDelete:0})
}